// pages/index/index.js
Page({
  data: {
    isLoading: true
  },
  onLoad: function() {
    const app = getApp();
    if (app.globalData.questions) {
      this.setData({
        isLoading: false
      });
    } else {
      // 监听题库加载完成
      const that = this;
      const timer = setInterval(function() {
        if (app.globalData.questions) {
          that.setData({
            isLoading: false
          });
          clearInterval(timer);
        }
      }, 500);
    }
  },
  startExam: function() {
    const app = getApp();
    if (!app.globalData.questions) {
      wx.showToast({
        title: '题库加载中，请稍候',
        icon: 'none'
      });
      return;
    }

    // 随机选择题目
    console.log('app.globalData.questions:', app.globalData.questions);
    const { single_choice_one, single_choice_two, multiple_choice } = app.globalData.questions || {};

    // 检查题库数据是否完整
    console.log('single_choice_one:', single_choice_one);
    console.log('single_choice_two:', single_choice_two);
    console.log('multiple_choice:', multiple_choice);

    if (!single_choice_one || !single_choice_two || !multiple_choice) {
      wx.showToast({
        title: '题库数据不完整',
        icon: 'none'
      });
      console.error('题库数据不完整:');
      if (!single_choice_one) console.error('- 缺少单选题一');
      if (!single_choice_two) console.error('- 缺少单选题二');
      if (!multiple_choice) console.error('- 缺少多选题');
      return;
    }

    // 随机选择25道单选题一
    const selectedSingleOne = this.randomSelect(single_choice_one, 25);
    // 随机选择20道单选题二
    const selectedSingleTwo = this.randomSelect(single_choice_two, 20);
    // 全部5道多选题，并重新编号id以避免与单选题重叠
    const selectedMultiple = [...multiple_choice].map((q, index) => ({
      ...q,
      id: 100 + index // 多选题id从100开始
    }));

    // 合并题目，并确保多选题在最后
    const examQuestions = [...selectedSingleOne, ...selectedSingleTwo, ...selectedMultiple];

    // 打乱单选题的顺序
    this.shuffleArray(selectedSingleOne);
    this.shuffleArray(selectedSingleTwo);

    // 设置全局数据
    app.globalData.examQuestions = examQuestions;
    app.globalData.userAnswers = {};
    app.globalData.startTime = Date.now();
    app.globalData.isExamStarted = true;

    // 跳转到考试页面
    wx.navigateTo({
      url: '/pages/exam/exam'
    });
  },
  // 随机选择指定数量的题目
  randomSelect: function(array, count) {
    // 确保array是一个数组
    if (!Array.isArray(array)) {
      console.error('randomSelect: 参数不是数组');
      return [];
    }
    // 处理空数组情况
    if (array.length === 0) {
      return [];
    }
    // 确保count是一个正整数
    count = Math.max(1, Math.min(count, array.length));
    const shuffled = [...array].sort(() => 0.5 - Math.random());
    return shuffled.slice(0, count);
  },
  // 打乱数组顺序
  shuffleArray: function(array) {
    for (let i = array.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [array[i], array[j]] = [array[j], array[i]];
    }
  }
})